package org.icop.virtdoc;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.tartarus.snowball.SnowballProgram;

public class VirtualDocParser {
    	
	private static VirtualDocParser eInstance = null;
	
	public static VirtualDocParser getInstance() {
		if (eInstance == null)
			eInstance = new VirtualDocParser();
		
		return eInstance;
	}
			
	public List<String> parseDocEntry(String entry) {
		List<String> tmp = new ArrayList<String>();
		
		tmp.addAll(Tokenizer.getInstance().tokenize(entry));
		
		List<String> result = new ArrayList<String>();
		
		for (String s : tmp)
			result.add(s.toLowerCase());

		if (VirtualDocParams.useStopwords)
			StopwordHandler.getInstance().filterStopWords(tmp);
		
		if (VirtualDocParams.useStemming)
			applyStemming(tmp);
				
		return result;
	}
		
	protected void applyStemming(List<String> terms) {
        try {
            Class<?> stemClass = Class.forName("org.tartarus.snowball.ext." + VirtualDocParams.stemmingLanguage + "Stemmer");
            SnowballProgram stemmer = (SnowballProgram) stemClass.newInstance();
            Method stemMethod = stemClass.getMethod("stem", new Class[0]);
            Object[] emptyArgs = new Object[0];
            for (int i = 0; i < terms.size(); i++) {
                stemmer.setCurrent(terms.get(i));
                stemMethod.invoke(stemmer, emptyArgs);
                terms.set(i, stemmer.getCurrent());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}
